const express = require('express');
const router = express.Router();

const batchController = require('../controllers/batchController');
const { 
  authenticateToken,
  requireFarmer,
  requireLogistics,
  requireMerchant,
  optionalAuth
} = require('../middleware/auth');
const { 
  validateBatchCreation,
  validateLogisticsRecord,
  validateSalesRecord,
  validateSearch,
  validatePagination,
  handleValidationErrors
} = require('../middleware/validation');
const { body, param } = require('express-validator');

/**
 * @route   POST /api/v1/batches
 * @desc    创建茶叶批次
 * @access  Private (Farmer, Admin)
 */
router.post(
  '/',
  authenticateToken,
  requireFarmer,
  validateBatchCreation,
  batchController.createBatch
);

/**
 * @route   GET /api/v1/batches
 * @desc    获取茶叶批次列表
 * @access  Private
 */
router.get(
  '/',
  authenticateToken,
  validatePagination,
  validateSearch,
  batchController.getBatchList
);

/**
 * @route   GET /api/v1/batches/search
 * @desc    搜索茶叶批次
 * @access  Private
 */
router.get(
  '/search',
  authenticateToken,
  [
    ...validatePagination.slice(0, -1), // 去掉handleValidationErrors
    ...validateSearch.slice(0, -1),     // 去掉handleValidationErrors
    handleValidationErrors
  ],
  batchController.searchBatches
);

/**
 * @route   GET /api/v1/batches/stats
 * @desc    获取批次统计信息
 * @access  Private
 */
router.get(
  '/stats',
  authenticateToken,
  batchController.getBatchStats
);

/**
 * @route   GET /api/v1/batches/:batchId
 * @desc    获取茶叶批次详情
 * @access  Private
 */
router.get(
  '/:batchId',
  authenticateToken,
  batchController.getBatchById
);

/**
 * @route   PUT /api/v1/batches/:batchId
 * @desc    更新茶叶批次基本信息
 * @access  Private (Farmer - Owner, Admin)
 */
router.put(
  '/:batchId',
  authenticateToken,
  [
    param('batchId')
      .custom((value) => {
        const isObjectId = /^[0-9a-fA-F]{24}$/.test(value);
        const isBatchId = /^TEA[0-9A-Z]{6,14}$/.test(value);
        
        if (!isObjectId && !isBatchId) {
          throw new Error('批次ID格式无效');
        }
        return true;
      }),
      
    body('name')
      .optional()
      .trim()
      .isLength({ min: 1, max: 100 })
      .withMessage('茶叶名称长度必须在1-100个字符之间'),
      
    body('variety')
      .optional()
      .trim()
      .isLength({ min: 1, max: 50 })
      .withMessage('茶叶品种长度必须在1-50个字符之间'),
      
    body('grade')
      .optional()
      .isIn(['特级', '一级', '二级', '三级', '其他'])
      .withMessage('茶叶等级必须是: 特级, 一级, 二级, 三级, 其他 之一'),
      
    body('description')
      .optional()
      .trim()
      .isLength({ max: 1000 })
      .withMessage('描述长度不能超过1000个字符'),
      
    handleValidationErrors
  ],
  batchController.updateBatch
);

/**
 * @route   POST /api/v1/batches/:batchId/production
 * @desc    添加生产记录
 * @access  Private (Farmer, Admin)
 */
router.post(
  '/:batchId/production',
  authenticateToken,
  requireFarmer,
  [
    param('batchId')
      .custom((value) => {
        const isObjectId = /^[0-9a-fA-F]{24}$/.test(value);
        const isBatchId = /^TEA[0-9A-Z]{6,14}$/.test(value);
        
        if (!isObjectId && !isBatchId) {
          throw new Error('批次ID格式无效');
        }
        return true;
      }),
      
    body('harvestDate')
      .isISO8601()
      .withMessage('采摘日期格式无效')
      .custom((value) => {
        const date = new Date(value);
        const now = new Date();
        if (date > now) {
          throw new Error('采摘日期不能是未来时间');
        }
        return true;
      }),
      
    body('processingMethod')
      .optional()
      .trim()
      .isLength({ max: 200 })
      .withMessage('加工工艺描述不能超过200个字符'),
      
    body('processingDate')
      .optional()
      .isISO8601()
      .withMessage('加工日期格式无效'),
      
    body('qualityGrade')
      .optional()
      .isIn(['特级', '一级', '二级', '三级'])
      .withMessage('质量等级必须是: 特级, 一级, 二级, 三级 之一'),
      
    body('weight')
      .optional()
      .isNumeric()
      .custom((value) => {
        if (parseFloat(value) <= 0) {
          throw new Error('重量必须大于0');
        }
        return true;
      }),
      
    body('notes')
      .optional()
      .trim()
      .isLength({ max: 500 })
      .withMessage('备注长度不能超过500个字符'),
      
    handleValidationErrors
  ],
  batchController.addProductionRecord
);

/**
 * @route   POST /api/v1/batches/:batchId/logistics
 * @desc    添加物流记录
 * @access  Private (Logistics, Admin)
 */
router.post(
  '/:batchId/logistics',
  authenticateToken,
  requireLogistics,
  [
    param('batchId')
      .custom((value) => {
        const isObjectId = /^[0-9a-fA-F]{24}$/.test(value);
        const isBatchId = /^TEA[0-9A-Z]{6,14}$/.test(value);
        
        if (!isObjectId && !isBatchId) {
          throw new Error('批次ID格式无效');
        }
        return true;
      }),
    ...validateLogisticsRecord.slice(1) // 跳过param验证，使用上面的自定义验证
  ],
  batchController.addLogisticsRecord
);

/**
 * @route   POST /api/v1/batches/:batchId/sales
 * @desc    添加销售记录
 * @access  Private (Merchant, Admin)
 */
router.post(
  '/:batchId/sales',
  authenticateToken,
  requireMerchant,
  [
    param('batchId')
      .custom((value) => {
        const isObjectId = /^[0-9a-fA-F]{24}$/.test(value);
        const isBatchId = /^TEA[0-9A-Z]{6,14}$/.test(value);
        
        if (!isObjectId && !isBatchId) {
          throw new Error('批次ID格式无效');
        }
        return true;
      }),
    ...validateSalesRecord.slice(1) // 跳过param验证，使用上面的自定义验证
  ],
  batchController.addSalesRecord
);

/**
 * @route   GET /api/v1/batches/public/:batchId
 * @desc    获取茶叶批次公开信息（消费者查询）
 * @access  Public
 */
router.get(
  '/public/:batchId',
  optionalAuth,
  [
    param('batchId')
      .custom((value) => {
        const isObjectId = /^[0-9a-fA-F]{24}$/.test(value);
        const isBatchId = /^TEA[0-9A-Z]{6,14}$/.test(value);
        
        if (!isObjectId && !isBatchId) {
          throw new Error('批次ID格式无效');
        }
        return true;
      }),
    handleValidationErrors
  ],
  async (req, res, next) => {
    // 为公开查询设置特殊权限
    req.user = req.user || { role: 'consumer', _id: null };
    next();
  },
  batchController.getBatchById
);

module.exports = router;